/**********************************
* klassenApp jQuery plugin
* A. Saebu 2014
***********************************/

//scope beperken : $, klassen, klassenhtml, opdrachten komen uit de globale context
(function ( $, klassen, klassenhtml, opdrachten, sidebar ) {


	//nieuwe jQuery functie/plugin declareren en implementeren
	$.fn.klassenApp = function( options ) {
		var klas, klashtml, llnOpdrachten = {opdr1: [] ,opdr2: [] }, t=0;
		/* default settings die via de options kunnen worden overschreven */
		var settings = $.extend({
			// These are the defaults.
				modus: "lln",
				modusSelector: 'modus-link',
				taskSelector: '.tasks .list-group-item',
				lijsten: ['lln-lijst','php-lijst','js-lijst'], // lijsten aan rechterzijde van de pagina
				activeklas: "IO1B4",
				activelln: '',
				klasSelector: ".klassen-nav a",
				container: '.klassenApp',
				imageSelector: 'img[id*="ll"]',
				imageClasses: ['present', 'not-present', 'active'],
				ttsUrl: 'http://tts-api.com/tts.mp3?q='
			}, options );
			
		var maakLlnLijst = function (klas) {

			for (var i=0; i< klas.length; i++) {
				//console.log(klas[i].naam);
				$('.lln-lijst').append('<a id="li'+ klas[i].nummer+'" class="list-group-item">'+ klas[i].naam+'</a>')
			}		
		}
		
		var truncateLijsten = function() {
			for (  i in settings.lijsten ) {
				$("."+settings.lijsten[i]).children().remove();
			}
		}
		
		var removeImageClasses = function() {
			for (i in settings.imageClasses) {
					$(settings.imageSelector).removeClass(settings.imageClasses[i]);
			}
		}

		var initOpdrachten = function () {
			settings.activelln = '';
			//truncateLijsten();
			removeImageClasses();
			//sublijst eerst opschonen
			$('.' + settings.modus +'-lijst').children().remove();
			//vervolgens weer opnieuw opbouwen
			initTasks();
			
			setActiveListener();
			setTasksListener();
		}

		
		var initPhp = function () {
			settings.activelln = '';
			truncateLijsten();
			removeImageClasses();
			//console.log(opdrachten);
			var myTasks = opdrachten[settings.modus]; 
			for (var i=0; i< myTasks.length; i++) {
				$('.php-lijst').append('<a id="php-'+ i +'" class="list-group-item">'+ myTasks[i] +'</a>')
			}
			setActiveListener();
			setTasksListener();
		}

		var setActiveListener = function() {
			$(settings.imageSelector).unbind("click");
			$(settings.imageSelector).click(function() {
					$(settings.imageSelector).removeClass('active');

					$(this).addClass('active');
					settings.activelln = $(this).attr('id').substr(2);
					//console.log(settings.activelln);
					$(settings.taskSelector).removeClass('active');
					
					getllnOpdrachten(settings.activelln);
					
					setActiveTasks()					
					
			});
		}

		var setActiveTasks = function() {
			console.log(settings.modus);
			var aTasksDone = llnOpdrachten[settings.modus];
			//console.log(aTasksDone);		
			$(settings.taskSelector).each(function () {
							var task = $(this).html();
							for (var i=0; i< aTasksDone.length; i++) {
								if (task == aTasksDone[i]) {
									$(this).addClass('active');
								}
							}
			})		
		}
		
		// Ophalen van info omtrent leerling gerelateerde info (bijv opdrachten) uit de localstorage
		var getllnOpdrachten = function(id) {
				if (localStorage[id]) {
					llnOpdrachten = JSON.parse(localStorage[id]);
				}
				else {
					llnOpdrachten =  initLlnOpdrachten(); //bijvoorbeeld {php:[], js: []};
				}
		}
		
		//Initieert llnOpdrachten op een generieke manier
		var initLlnOpdrachten = function() {
			//kopieren van de opdrachten object
			var anObj = opdrachten.slice();
			for (i in anObj) {
				anObj[i] = [];
			}
			console.log(anObj);
			return anObj;
		}
		
		var setTasksListener = function() {
			$(settings.taskSelector).click(function() {

					if (!$(this).hasClass('active')) {
						llnOpdrachten[settings.modus].push($(this).html());
						var selfie = $(this);
						if (settings.activelln) {
							$.getJSON("scripts/add.php",{id: settings.activelln, jsonValue: llnOpdrachten },function(obj) {
								//console.log(obj);
								if (obj.status==0) {
									localStorage[settings.activelln] = JSON.stringify(llnOpdrachten);
									selfie.addClass('active');
								}
								else {
									//console.log(obj.message);
								}
							});
						}

					}
					else {
						if (confirm('Undo opdracht gedaan ?')) {							
							var jsOpdrachten = llnOpdrachten.opdr1;							
							//verwijder uit de array
							var ix = jsOpdrachten.indexOf($(this).text());
							if (ix >= 0) {
								jsOpdrachten.splice(ix,1);
							}
							llnOpdrachten.opdr1 = jsOpdrachten;
							//uit de localstorage halen
							localStorage[settings.activelln] = JSON.stringify(llnOpdrachten);	
							//de class verwijderen
							$(this).removeClass('active');
						}
					}
			});	
		}
		
		var initLocal = function () {
			settings.activelln = '';
			truncateLijsten();
			removeImageClasses();
			
			initTasks();
			
			setActiveListener();
			setTasksListener();
		}
		
		var initTasks = function() {
			var myTasks = opdrachten[settings.modus]; 
			for (var i=0; i< myTasks.length; i++) {
				$('.'+ settings.modus +'-lijst').append('<a id="js-'+ i +'" class="list-group-item">'+ myTasks[i] +'</a>')
			}				
		}

		var initKeuzes = function () {
			settings.activelln = '';
			truncateLijsten();
			removeImageClasses();

			initTasks();
			
			setActiveListener();
			setTasksListener();
		}

		var initKlas = function () {
		
			klashtml = klassenhtml[settings.activeklas];
			$('.modus-link').removeClass('active');
			$('#presentie').addClass('active');
			
			$(settings.container).children().remove();	
			truncateLijsten();

			$(settings.container).append(klashtml);	// de html van de pasfotos van alle leerlingen 
			$(settings.imageSelector).toggleClass('not-present');

			klas = klassen[settings.activeklas];
			maakLlnLijst(klas);

			$(settings.imageSelector).unbind("click");			
			$(settings.imageSelector).click(function() {
					$(this).toggleClass('present');
					$(this).toggleClass('not-present');
					settings.activelln = $(this).attr('id').substr(2);
					
					$('#li'+$(this).attr('id').substr(2)).toggle();
					//console.log('#li'+$(this).attr('id').substr(2));
					ttsLn(getNaamLln(settings.activelln));
			});
						

		}		
		
		var getNaamLln = function(nummer) {
			var theKlas = klassen[settings.activeklas];
			for (var i=0; i< theKlas.length; i++) {
				if (nummer == theKlas[i].nummer) {
					return theKlas[i].naam;
				}
			}
			return 'xxx';
		}
		
		var ttsLn = function (naam) {
			strWelkom = ['Hoe gaat het ?', 'Meester', 'Hallo', 'Alles goed ?', 'Top, dat je er bent,', 'Perfect', 'Super,'];
			$('video').remove();
			$('body').append('<video style="display:none;" autoplay="" name="media"><source src="' + settings.ttsUrl + encodeURIComponent(strWelkom[t++]+' '+ naam) +'" type="audio/mpeg"></video>');
			t = t>=strWelkom.length ? t=0 : t;
		}
		
		
		$(settings.klasSelector).click(function() {
			$(this).parent().siblings().removeClass('active');
			$(this).parent().addClass('active');
			settings.activeklas = $(this).attr('data-klas');
			initKlas();
		});
		
		
		var initModus = function() {
		
			switch (settings.modus) {
				case 'lln':
					initKlas();
					break;
				case 'php':
					initPhp();
					break;
				case 'ao':
					initOpdrachten();
					break;
				case 'local':
					initLocal();
					break;
				case 'keuzes':
					initKeuzes();
					break;
				default:
					break;
			}
		};
		
		var initSidebar = function () {
			var lg = '';
			var lgsub = '';
			var act = 'active';
				for (i in sidebar) {
					//alert(sidebar[i].id);
					//alert(sidebar[i].title);
					lg += '<a href="#" id="'+ sidebar[i].id +'" class="list-group-item '+ act +' '+ settings.modusSelector +'">' + sidebar[i].title + '</a>';
					act = '';

					lgsub += '<div class="list-group '+ sidebar[i].id+'-lijst '+ sidebar[i].class +'"></div>';
				}
				
			$('.list-group:first').html(lg);
			$('.list-group:first').after(lgsub);
			//listener op de sidebar opties 
			$('.'+settings.modusSelector).click(function() {
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
				settings.modus = $(this).attr('id');
				//console.log(settings.modus);
				initModus();
			});

		};

		var init = function() {
			initSidebar();
			//ao opdrachten
			settings.modus = 'ao';
			initKlas();
		};


		init();
		return this;
	};
}( jQuery, klassen, klassenhtml,opdrachten, sidebar));	
